package com.joplus.housekeeper.xmpp;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.format.Time;
import android.util.Base64;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.hyphenate.chatuidemo.ui.ChatActivityNew;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.util.ImageUtils;
import com.joplus.housekeeper.bean.ChatCard;
import com.joplus.housekeeper.bean.MessageRecordListBean;
import com.joplus.housekeeper.bean.RecordListBean;
import com.joplus.housekeeper.bean.XmppMessage;
import com.joplus.housekeeper.bean.XmppUser;
import com.joplus.housekeeper.network.RequestHelper;
import com.joplus.housekeeper.network.TextCallback;
import com.joplus.housekeeper.utils.Imageutils;
import com.joplus.housekeeper.utils.RealmHelper;
import com.joplus.housekeeper.utils.RxBus;
import com.joplus.housekeeper.utils.StringUtils;
import com.joplus.housekeeper.utils.T;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.realm.RealmResults;

/**
 * author： ccm
 * time： 2017/7/12.
 * description：
 */

public class SmackChatManagerListener implements ChatManagerListener {

    private String body;

    private String from;


    @Override
    public void chatCreated(Chat chat, boolean createdLocally) {

        chat.addMessageListener(new ChatMessageListener() {

            @Override
            public void processMessage(Chat chat, final Message message) {


                {

                    try {
                        body = message.getBody();
                        ExtensionElement extension = message.getExtension("extension", "urn:xmpp:joplus:extension");
                        Log.e("smack", "processMessage: " + extension.getElementName());
                        Log.e("smack", "processMessage: " + extension.getNamespace());


                        Observable.just(body).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {


                            @Override
                            public void accept(String s) throws Exception {
                                if (!StringUtils.isEmpty(body)) {

                                    //  CUSTOMER_NAME = message.getFrom();

                                    from = message.getFrom();
                                    final MessageRecordListBean xmppMessage = new Gson().fromJson(body, MessageRecordListBean.class);
                                    //   final XmppMessage xmppMessage = new Gson().fromJson(body, XmppMessage.class);
                                    //    xmppMessage.setMessageId(UUID.randomUUID().toString());
                                    String userId = from.split("@")[0];
                                    String s2 = UUID.randomUUID().toString().replaceAll("-", "");
                                    xmppMessage.setMessageId(s2);
                                    xmppMessage.setMessageDatetime(System.currentTimeMillis());


                                    if (xmppMessage.getType() == 3) {

                                        final byte[] decode = Base64.decode(xmppMessage.getContent(), Base64.DEFAULT);
                                        String content = new String(decode, "UTF-8");
                                        String picname = System.currentTimeMillis() + ".jpg";
                                        final File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/image/" + picname);
                                        file.getParentFile().mkdirs();
                                        xmppMessage.setContent(file.getAbsolutePath());

                                        RequestHelper.getInstance().downLoad(content, file, new TextCallback() {
                                            @Override
                                            public void onFailure(String responseString) {

                                            }

                                            @Override
                                            public void onSuccess(Object responseString) {
                                                //     ChatActivityNew.activityInstance.sendPic2Custome(file.getAbsoluteFile());
                                            }
                                        });
                                        if (ChatActivityNew.activityInstance != null && isForeground(ChatActivityNew.activityInstance, "com.hyphenate.chatuidemo.ui.ChatActivityNew") && ChatActivityNew.activityInstance.user.getAccountId().equals(xmppMessage.getAccountId())) {
                                            ChatActivityNew.activityInstance.sendPic2Custome(file.getAbsoluteFile());


                                        } else {
                                            EaseUI.getInstance().getNotifier().onNewMsg(xmppMessage.change2EmMessage());
                                            RxBus.getInstance().send(xmppMessage);
                                        }


                                    } else if (xmppMessage.getType() == 2) {

                                        File skRoot = Environment.getExternalStorageDirectory();
                                        String voiceFileName = getVoiceFileName("customer-service1");
                                        String filePath = skRoot.getAbsolutePath() + "/voice/" + voiceFileName;
                                        base642File(xmppMessage.getContent(), skRoot.getAbsolutePath() + "/voice/" + voiceFileName);
                                        xmppMessage.setContent(filePath);

                                        if (ChatActivityNew.activityInstance != null && isForeground(ChatActivityNew.activityInstance, "com.hyphenate.chatuidemo.ui.ChatActivityNew") && ChatActivityNew.activityInstance.user.getAccountId().equals(xmppMessage.getAccountId())) {
                                            ChatActivityNew.activityInstance.insertVoice(filePath, xmppMessage.getDuration(), "kefu1");
                                        } else {
                                            EaseUI.getInstance().getNotifier().onNewMsg(xmppMessage.change2EmMessage());
                                            RxBus.getInstance().send(xmppMessage);
                                        }


                                    } else if (xmppMessage.getType() == 8) {

                                        final byte[] decode = Base64.decode(xmppMessage.getContent(), Base64.DEFAULT);
                                        String content = new String(decode, "UTF-8");


                                        ChatCard chatCard = new ChatCard();
                                        chatCard.setSubject("gif");
                                        chatCard.setMessage(content);
                                        Gson gson = new Gson();
                                        String s1 = gson.toJson(chatCard);
                                        xmppMessage.setContent(s1);

                                        if (ChatActivityNew.activityInstance != null && isForeground(ChatActivityNew.activityInstance, "com.hyphenate.chatuidemo.ui.ChatActivityNew") && ChatActivityNew.activityInstance.user.getAccountId().equals(xmppMessage.getAccountId())) {
                                            ChatActivityNew.activityInstance.sendMessageToCustom(content);
                                        } else {

                                            EaseUI.getInstance().getNotifier().onNewMsg(xmppMessage.change2EmMessage());
                                            RxBus.getInstance().send(xmppMessage);
                                        }

                                    } else {
                                        final byte[] decode = Base64.decode(xmppMessage.getContent(), Base64.DEFAULT);
                                        String content = new String(decode, "UTF-8");

                                        xmppMessage.setContent(content);

                                        if (ChatActivityNew.activityInstance != null && isForeground(ChatActivityNew.activityInstance, "com.hyphenate.chatuidemo.ui.ChatActivityNew") && ChatActivityNew.activityInstance.user.getAccountId().equals(xmppMessage.getAccountId())) {
                                            ChatActivityNew.activityInstance.sendMessageToCustom(content);
                                        } else {
                                            EaseUI.getInstance().getNotifier().onNewMsg(xmppMessage.change2EmMessage());
                                            RxBus.getInstance().send(xmppMessage);
                                        }


                                    }

                                    RealmHelper.instance().insertNewMessage(xmppMessage);

                                } else {
                                    //body  是空 可能是发送消息后的回执
                                    SmackElement extension = (SmackElement) message.getExtension("extension");
                                    if ("response".equals(extension.getType())) {

                                    }


                                }
                            }
                        });


                    } catch (Exception e) {
                        Log.e("smack", "processMessage: " + e.toString());

                        {

                        }

                    }


                }


            }
        });
    }

    public Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    private String getVoiceFileName(String uid) {
        Time now = new Time();
        now.setToNow();
        return uid + now.toString().substring(0, 15) + ".amr";
    }

    private boolean isForeground(Activity context, String className) {
        if (context == null || StringUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }


        return false;
    }

    public void base642File(String code, String path) {

        byte[] buffer = Base64.decode(code, Base64.DEFAULT);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            out.write(buffer);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
